﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;

namespace System.ComponentModel.DataAnnotations
{
    [AttributeUsage(AttributeTargets.Property, Inherited = true)]
    public class ArrayMinLengh : ValidationAttribute
    {
        public ArrayMinLengh(int lenth)
        {
            Length = lenth;
        }

        public int Length { get; set; }
        public override bool RequiresValidationContext => true;

        public override string FormatErrorMessage(string name)
        {
            if (string.IsNullOrEmpty(ErrorMessage))
                return $"{name}长度至少为{Length}";
            return string.Format(ErrorMessage,Length);
        }

        public override bool IsValid(object value)
        {
            return value is IEnumerable;
        }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var enumer = value as IEnumerable;
            int i = 0;
            foreach (var item in enumer)
            {
                if (++i >= Length)
                {
                    return ValidationResult.Success;
                }
            }
            return new ValidationResult(null);
        }
    }
}
